package com.acme.bankapp.domain.bank;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import com.acme.BankApplication;
import com.acme.bankapp.service.bank.AccountDoesntExistsException;
import com.acme.bankapp.service.bank.BankReport;

public class BankServer {
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	public BankServer() {
	}

	void run() throws AccountDoesntExistsException {
		try {
			providerSocket = new ServerSocket(1234);
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println(connection.getInetAddress()
					+ " connected to server");
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Connection successful ");
			do {
				try {
					message = (String) in.readObject();
					System.out.println("recieved request from "
							+ connection.getInetAddress() + ": " + message);
					if (message.equals("printBank")) {
						sendMessage(BankReport.printBank(BankApplication.bank1));
					} else {
						sendMessage("Wrong request");
					}
				} catch (ClassNotFoundException classnot) {
					System.err.println("Sata recieved in unknown format");
				}
			} while (!message.equals("exit"));
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				providerSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("'" + msg + "' sent to "
					+ connection.getInetAddress());
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void startServer(Bank bank)
			throws AccountDoesntExistsException {
		BankServer server = new BankServer();
		while (true) {
			server.run();
		}
	}

}
